
/**
 * Module dependencies.
 */
var express = require('express');
var i18n=require('i18n');
i18n.configure({
    locales:['en-US', 'zh-CN'],  // setup some locales - other locales default to en_US silently
    defaultLocale: 'zh-CN',
    directory: './i18n',  // i18n 翻译文件目录，我的是 i18n， 可以写成其他的。
    updateFiles: false,
    indent: "\t",
    extension: '.json'  // 由于 JSON 不允许注释，所以用 js 会方便一点，也可以写成其他的，不过文件格式是 JSON
});
var routes = require('./routes');
//var partials = require('express-partials'); //新版本express layout--partials支持
var http = require('http');
var path = require('path');
var MongoStore =require('connect-mongo')(express);// session用户信息存入数据库依赖
var config=require('./config');
var flash=require('connect-flash');     //flash通知模块
var app = express();
//app.use(partials());

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(flash());
app.use(i18n.init);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.bodyParser({keepExtensions:true,uploadDir:'./public/images/user'}));//用户上传头像设置
app.use(express.cookieParser());//cookie解析中间件
app.use(express.session({       //提供会话支持
	secret:config.cookieSecret,
    cookie:{maxAge:1000*60*60*10},//10个小时
	store:new MongoStore({
		db:config.db
	})
}))
app.use(function(req,res,next){	      //注册全局变量
	var err = req.flash('error');
    var success = req.flash('success');
	res.locals.user = req.session.user;
	res.locals.error= err.length ? err : null;
	res.locals.success = success.length ? success : null;
	next();
});
app.use(function(req,res,next){
    if(req.path.indexOf('.')<0){
        req.setLocale(req.session.language);
    }
    var url=req.path;
    console.log(url);
    var reg=url.indexOf('.')<0&&url!='/about'&&url!='/z'&&url!='/forgetPassword'&&url!='/resetPassword'&&url!='/sendEmail'&&url!='/test'&&url!='/u'&&url!='/'&&url!='/reg'&&url!='/login'&&!req.session.user
    if(reg){
        req.flash('error',res.__('warn').app_nologin);
        return res.redirect('/')
    }
    if(req.session.user){
        if(url=='/reg'||url=='/'){
            req.flash('error',res.__('warn').app_login);
            return res.redirect('/findPartner')
        }
    }
    next();
})

app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
routes(app);
